package com.example.lib_image

import android.app.ActivityManager
import android.content.Context
import android.os.StatFs

/**
 * @author yaotianxue
 * @description
 * @date 2025/5/24
 */
object GlideCacheManager {
    // 默认缓存配置
    private const val DEFAULT_MEM_CACHE_SIZE = 24L * 1024 * 1024 // 24MB
    private const val DEFAULT_DISK_CACHE_SIZE = 250L * 1024 * 1024 // 250MB
    private const val LOW_MEMORY_DEVICE_MULTIPLIER = 0.5f
    private const val HIGH_MEMORY_DEVICE_MULTIPLIER = 5f

    /**
     * 计算内存缓存大小
     */
    fun calculateMemoryCacheSize(context: Context): Long {
        val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val memoryInfo = ActivityManager.MemoryInfo()
        activityManager.getMemoryInfo(memoryInfo)

        // 基础内存计算
        val baseCacheSize = when {
            activityManager.isLowRamDevice -> DEFAULT_MEM_CACHE_SIZE * LOW_MEMORY_DEVICE_MULTIPLIER   //低内存设备
            isHighMemoryDevice(context) -> DEFAULT_MEM_CACHE_SIZE * HIGH_MEMORY_DEVICE_MULTIPLIER //高内存设备
            else -> DEFAULT_MEM_CACHE_SIZE
        }.toLong()

        // 根据当前内存状态调整
        return if (memoryInfo.lowMemory) {
            (baseCacheSize * 0.7).toLong() // 内存紧张时减少缓存
        } else {
            baseCacheSize
        }
    }
    /**
     * 判断是否为高内存设备
     */
    private fun isHighMemoryDevice(context: Context): Boolean {
        val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val memoryInfo = ActivityManager.MemoryInfo()
        activityManager.getMemoryInfo(memoryInfo)

        // 总内存大于3GB视为高内存设备
        return memoryInfo.totalMem > 3L * 1024 * 1024 * 1024
    }

    /**
     * 计算磁盘缓存大小
     */
    private fun calculateDiskCacheSize(context: Context): Long {
        return try {
            // 获取缓存目录可用空间
            val cacheDir = context.cacheDir
            val stat = StatFs(cacheDir.path)
            val availableBlocks = stat.availableBlocksLong
            val blockSize = stat.blockSizeLong
            val availableSpace = availableBlocks * blockSize

            // 计算合适的缓存大小（可用空间的15%，但不超过1GB）
            minOf((availableSpace * 0.15).toLong(), 1024L * 1024 * 1024)
        } catch (e: Exception) {
            DEFAULT_DISK_CACHE_SIZE // 出错时返回默认值
        }
    }
    /**
     * 获取磁盘缓存配置
     * @return Pair<缓存大小, 缓存目录名称>
     */
    fun getDiskCacheConfig(context: Context): Pair<Long, String> {
        val cacheDir = "club_glide_cache" // 自定义缓存目录名
        val diskCacheSize = calculateDiskCacheSize(context)
        return Pair(diskCacheSize, cacheDir)
    }

    /**
     * 清除内存缓存（需要在主线程调用）
     */
    fun clearMemoryCache(context: Context) {
        GlideApp.get(context).clearMemory()
    }

    /**
     * 清除磁盘缓存（需要在后台线程调用）
     */
    fun clearDiskCache(context: Context) {
        GlideApp.get(context).clearDiskCache()
    }




}